// pmidi.m -- A simple command-line MIDI player for Mac OS X.
//
// David Siegel <djsiegel@gmail.com>
// Jonathan Coveney <jcoveney@gmail.com>
//

#import <Foundation/Foundation.h>
#import <AudioToolbox/AudioToolbox.h>

#define DEFAULT_WAIT 0.8

int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

	if (argc < 2) {
		NSLog (@"USAGE: pmidi midi_file.mid", argv[0]);
		return 1;
	}

    // Place optional play duration argument in wait.
	float wait = DEFAULT_WAIT;
	if (argc == 3)
		wait = [[NSString stringWithCString: argv[2]] floatValue];
	
    MusicPlayer player;
	MusicSequence sequence;
	NSData *data = [NSData dataWithContentsOfFile: [NSString stringWithCString: argv[1]]];

	if (NewMusicSequence (&sequence) != noErr)
		[NSException raise:@"play" format:@"Can't create MusicSequence"];
	if (MusicSequenceLoadSMFData (sequence, (CFDataRef) data) != noErr) 
		[NSException raise:@"play" format:@"Can't load MusicSequence"];
	if (NewMusicPlayer (&player) != noErr)
		[NSException raise:@"play" format:@"Can't create MusicPlayer"];
	if (MusicPlayerSetSequence (player, sequence) != noErr)
		[NSException raise:@"play" format:@"Can't set sequence for MusicPlayer"];
	if (MusicPlayerStart (player) != noErr)
		[NSException raise:@"play" format:@"Can't start MusicPlayer"];
	
	// I can't figure out when the sequence is over, so we just wait.
	[NSThread sleepForTimeInterval: wait];
	
    [pool drain];
    return 0;
}
